package Thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPool{

    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);

    //通过这个方法，把任务添加到队列中
    public void submit(Runnable runnable) throws InterruptedException {
        //这里的拒绝策略相当于第五中拒绝策略，阻塞等待
        queue.put(runnable);
    }

    public MyThreadPool(int n){
        //创建出n个线程
        for(int i = 0;i<n;i++){
            Thread t = new Thread(()->{
                try {
                    //让这个线程从队列中消费任务，并进行执行
                    Runnable runnable = queue.take();
                    runnable.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }

    }
}

public class Demo03 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool myThreadPool = new MyThreadPool(4);
        for(int i = 0;i<1000;i++){
            int id = i;
            myThreadPool.submit(new Runnable(){
                @Override
                public void run() {
                    //这里的i，是变量捕获，java中的变量捕获只能捕获final或者事实final变量
//                    System.out.println("执行任务"+i);
                    System.out.println("执行任务"+id);//将id作为i的备份即可捕获

                }
            });
        }

    }
}
